/**
 * Created by zxr on 16/11/15.
 */
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var resource = {};
var server = http.createServer(server);
var chatServer = require('./lib/chat_server');


  chatServer.listen(server);
function sendFile(res,filePath,fileContents){
	res.writeHead(200, {'Content-Type':mime.lookup(path.basename(filePath))});
	res.end(fileContents);
}

function server(req, res){
	var filePath = false;
	if (req.url == '/'){
		filePath = 'public/index.html'
	} else if (req.url == '/favicon.ico'){
		res.end();
	} else {
		filePath = 'public' + req.url;
	}
	var absPath = './' + filePath;
	serverStatic(res, resource, absPath);
}

function stat404(res){
	res.writeHead(400,'Content-Type','text/plain');
	res.end('No Find');
}
//提供静态文件服务
function serverStatic(res,resource,absPath){
	if (resource[absPath]){
		sendFile(res,absPath,resource[absPath]);
	} else {
		fs.exists(absPath,function(exists){
			if (exists){
				fs.readFile(absPath,function(err, data){
					if (err) {
						stat404(res);
					} else {
						resource[absPath] = data;
						sendFile(res, absPath, resource[absPath]);
					}
				})
			} else {
				stat404(res);
			}
		})
	}
}
// 进入聊天室的逻辑





server.listen('3021');
